﻿using Grpc.Core;
using Grpc.Net.Client;
using System;
using System.Threading.Tasks;

namespace GrpcGreeterClient
{
    class Program
    {
        static string _token;
        static DateTime _refreshtime;
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            //声明连接服务器的管道
            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            //实例化客户端
            var client = new Greeter.GreeterClient(channel);
            //获取token
            if (string.IsNullOrEmpty(_token) || _refreshtime < DateTime.Now)
            {
                await GetToken(client);
            }
            //jwt 验证参数
            var header = new Metadata() { new Metadata.Entry($"Authorization", $"Bearer {_token}") };
            //向服务器发送请求
            var sayHelloReply = await client.SayHelloAsync(new HelloRequest { Name = "222" }, header);
            Console.WriteLine(sayHelloReply.Message);
            Console.ReadKey();

        }
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        private static async Task GetToken(Greeter.GreeterClient client)
        {
            var reply = await client.GetTokenAsync(new GetTokenRequest { Username = "admin", Password = "admin" });
            Console.WriteLine(reply.Success);

            if (reply.Success)
            {
                Console.WriteLine(reply.Refreshtime);
                Console.WriteLine(reply.Tokenstring);
                _token = reply.Tokenstring;
                _refreshtime = reply.Refreshtime.ToDateTime();
            }
        }
    }
}
